package com.bootdo.lgs.ordertrace.controller;

import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.R;
import com.bootdo.lgs.order.model.LgsOrder;
import com.bootdo.lgs.order.model.OrderTraceUpdate;
import com.bootdo.lgs.order.service.OrderService;
import com.bootdo.lgs.ordertrace.model.OrderTraceQuery;
import com.bootdo.lgs.ordertrace.service.OrderTraceService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author bootdo 1992lcg@163.com
 */
@Controller
public class OrderTraceController extends BaseController {

    @Autowired
    OrderTraceService orderTraceService;

    @Autowired
    OrderService orderService;

    @PostMapping("/lgs/orderTrace/getData")
    @ResponseBody
    List getData(OrderTraceQuery condition) {
        return orderTraceService.getListFromDb(condition);
    }

    @GetMapping("/lgs/orderTrace/edit")
    String trackEdit(@RequestParam Long trackId, Model model) {
        OrderTraceQuery condition = new OrderTraceQuery();
        condition.setOrderId(trackId);
        model.addAttribute("tracking", orderTraceService.getById(trackId));
        return "lgs/trackEdit";
    }

    @GetMapping("/lgs/orderTrace/add")
    String trackAdd(@RequestParam Long orderId, Model model) {
        model.addAttribute("orderId", orderId);
        return "lgs/trackAdd";
    }

    @PostMapping("/lgs/orderTrace/addTrack")
    @ResponseBody
    R addTrack(@RequestBody OrderTraceUpdate dto) {
        Map<String, Object> condition = Maps.newHashMap();
        condition.put("orderId", dto.getOrderId());
        condition.put("context", dto.getContent());
        condition.put("ftime", dto.getFtime());

        if (!orderTraceService.saveOrderTrace(Collections.singletonList(condition))) {
            return R.error();
        }
        if("7".equals(dto.getStatus())){ //为已签收时 更新订单状态为已签收
            LgsOrder condition2 = new LgsOrder();
            condition2.setId(dto.getOrderId());
            condition2.setLgs_status(dto.getStatus());
            return orderService.update(condition2, getUser()) ? R.ok() : R.error();
        }
        return R.ok();
    }

    @PostMapping("/lgs/orderTrace/modifyTrack")
    @ResponseBody
    R modifyTrack(@RequestBody OrderTraceUpdate dto) {
        Map<String, Object> condition = Maps.newHashMap();
        condition.put("id", dto.getTrackId());
        condition.put("context", dto.getContent());
        return orderTraceService.modify(condition) ? R.ok() : R.error();
    }

    @PostMapping("/lgs/orderTrace/deleteTrack")
    @ResponseBody
    R deleteTrack(@RequestParam Long trackId) {
        return orderTraceService.delete(trackId) ? R.ok() : R.error();
    }
}